package com.iot.ammeter.view

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.lifecycle.lifecycleScope
import com.iot.ammeter.IApplication
import com.iot.ammeter.R
import com.iot.ammeter.network.Repository
import com.iot.ammeter.storage.*
import kotlinx.coroutines.launch

/**
 * 启动页：
 * - 处理黑白屏、闪屏
 * - 根据用户登录状态跳转到对应 Activity
 */
@ExperimentalMaterial3Api
class StartActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_start)

        IApplication.token = readUserToken()

        if (IApplication.token == null || IApplication.lastMonthInfo == null) {
            // 没有 token 时转到登录页
            startActivity(Intent(this, AuthActivity::class.java))
            this.finish()
        } else {
            getBaseInfoLocally()
            updateBaseInfo()
        }
    }

    /**
     * 从 MMKV 获取用户信息和设备信息进行初始化
     */
    private fun getBaseInfoLocally() = readUserInfoLocally()?.let {
        IApplication.userInfo = it
        it.deviceId?.let {
            IApplication.deviceInfo = readDeviceInfoLocally()
        }
    }

    /**
     * 从网络用户和设备数据，并更新到 MMKV 中，
     * 无论获取成功或失败，最后都进入主页
     */
    private fun updateBaseInfo() = lifecycleScope.launch {
        Repository.getBaseInfo(
            IApplication.token!!,
            onFinished = {
                startActivity(Intent(this@StartActivity, MainActivity::class.java))
                this@StartActivity.finish()
            }
        ) { userInfo, deviceInfo, lastMonthInfo ->
            IApplication.userInfo = userInfo
            IApplication.deviceInfo = deviceInfo
            IApplication.lastMonthInfo = lastMonthInfo
            writeUserInfoLocally(userInfo)
            writeDeviceInfoLocally(deviceInfo)
            writeLastMonthInfoLocally(lastMonthInfo)
            // TODO("忘记少了什么逻辑")
        }
    }
}